<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            margin: 0;
        }
        .box {
            width: 1200px;
            height: 20px;
            border: 1px solid rgb(240, 107, 107);
            border-radius: 10px;
            margin-top: 30px;
        }
        .progress {
            width: 0;
            height: 20px;
            transition: 0.2s linear;
            background-color: rgb(238, 44, 44);
            border-radius: 10px;
        }
    </style>
</head>
<body>
    <input type="file" id="filel">
    <button id="btn-upload">上传文件</button>
    <div class="box">
        <div class="progress"></div>
    </div>
    <script>
        const url = 'http://www.liulongbin.top:3006/api/upload/avatar';
        const inp = document.querySelector('#filel');
        const btn = document.querySelector('#btn-upload');
        const progressBox = document.querySelector('.progress');
        btn.addEventListener('click', function () {
            // const files = inp.files;
            const {files} = inp;
            console.log(files);

            if (files[0].size > 500 * 1024) {
                alert('文件大于500k不能上传');
                return;
            }

            const fd = new FormData();
            fd.append('hello', files[0]);

            
            const xhr = new XMLHttpRequest();
            xhr.open('POST', url);

            // 上传进度条 文件上传必须在发送前绑定
            xhr.upload.onprogress = function (e) {
                const progress = e.loaded / e.total;
                progressBox.setAttribute('style', `width: ${ progress * 100 }%`);
            }

            xhr.send(fd);

            xhr.onreadystatechange = function () {
               if (xhr.readyState === 4 && xhr.status === 200) {
                   console.log(JSON.parse(xhr.responseText));
               }
           }

        })
    </script>
</body>
</html>